import { TaroElement } from "@tarojs/runtime"
import { getWindowInfo } from "./layout"

export function setupHtml() {
  if (Taro.env.TARO_ENV !== 'h5') {
    require("@tarojs/taro/html.css")
  }
  if (Taro.env.TARO_ENV === 'weapp') {
    htmlTransform()
  }
}
function htmlTransform() {
  Taro.options.html!.transformElement = (el: TaroElement) => {
    if (el.nodeName === "image") {
      const styleWidth: string = el.style.getPropertyValue("width") || ""
      const imageSrc = el.getAttribute("src")
      let hasParentElement = false
      if (el.parentElement) {
        if (el.parentElement.parentElement) {
          hasParentElement = true
        }
      }
      if (!hasParentElement || styleWidth.endsWith("%")) {
        el.setAttribute("mode", "widthFix")
      }
      const { width: windowWidth } = getWindowInfo()
      const pxMatch = styleWidth.match(/(\d+)px/)
      if (pxMatch) {
        const pxValue = Number(pxMatch[1])
        setWidth(pxValue)
      } else {
        el.addEventListener(
          "load",
          function (res) {
            const { width } = res.detail
            setWidth(width)
          },
          false
        )
      }
      el.addEventListener(
        "tap",
        function () {
          const url = imageSrc
          if (url) {
            Taro.previewImage({
              current: url,
              urls: [url]
            })
          }
        },
        false
      )
      function setWidth(width: number) {
        let w = "100%"
        if (windowWidth > width) {
          w = width + "px"
        }
        el.style.setProperty("width", w)
      }
    }
    return el
  }
}
